class DataHelper{
dataKey:string;
primaryKey:number;
// let  dh = new DataHelper("plData","id")
constructor(dataKey:string, primaryKey:number){this.dataKey=dataKey;this.primaryKey=primaryKey}
//读取数据
readData():any{
  //读取本地数据
  let strData :string | null = localStorage.getItem(this.dataKey);
  //将读取的字符转对象
  let arrData :any = [];
  if(strData!=null){
    arrData = JSON.parse(strData);
  }
  //返回对象
  return arrData;
}
//保存数据
  saveData(arrData:Array<Object>):void{
    //将数组转字符串
    let str :string = JSON.stringify(arrData);
    //字符串存本地localstorage
    localStorage.setItem(this.dataKey,str )
  }
//增加数据
  addData(conStr:string):number{
    //读取本地数据
    let arr:any = this.readData();
    //创建评论对象
    let obj :Object = {
      content:conStr
    }
    //自动生产主键id
    let newId = arr.length>0?arr[arr.length-1][this.primaryKey]+1:1;
    //将新id通过中括号添加
    obj[this.primaryKey] = newId;
    //将新的评论对象加入评论数据
    arr.push(obj);
    //将评论数据存入本地localstrorage
    this.saveData(arr)
    //返回id
    return newId;
  }

  removeDataById(id:string|number): boolean{
    let arr = this.readData();
    let index = arr.findIndex((ele)=>{
        return ele[this.primaryKey]  ==id;
    })
    if(index>-1){
      arr.splice(index,1);
      //保存到本地
      this.saveData(arr);
      return true;
    }

    return false;
  }
}

